/**=========================================================
 * Controller: SystemUserController
  =========================================================*/
App.controller('SystemUserController', ['$scope', 'toaster', 'ngDialog', 'Utils', 'HttpUtils', 'DialogUtils', 'SimpleUiGrid',
    function($scope, toaster, ngDialog, utils, httpUtils, dialogUtils, simpleUiGridService) {
        $scope.currentUser = {};
        //===========================userGrid=================================            
        var userGridColumns = [
            {
                displayName: '用户编号',
                field: 'code',
                width: '150'
            },
            {
                displayName: '中文名称',
                field: 'cnname',
                width: '150'
            },
            {
                displayName: '邮箱',
                field: 'email',
                width: '250'
            },
            {
                displayName: '工种',
                field: 'title',
                width: '70'
            },
            {
                displayName: '备注',
                field: 'remark'
            },
            {
                displayName: '状态',
                field: 'status',
                width: '80'
            },
            { 
                name: '', 
                field: 'widgets', 
                width: '150',
                enableCellEdit: false,
                cellTemplate: '\
                    <div class="ui-grid-cell-contents" style="text-align:center;">\
                        <button ng-click="grid.appScope.selectRole(row.entity)" title="维护角色" class="btn btn-xs btn-success">\
                            <em class="fa fa-users"></em>\
                        </button>\
                        <button ng-click="grid.appScope.changePassword(row.entity)" title="修改密码" class="btn btn-xs btn-warning">\
                            <em class="fa fa-key"></em>\
                        </button>\
                        <button ng-click="grid.appScope.saveUser(row.entity)" title="保存" class="btn btn-xs btn-info">\
                            <em class="fa fa-save"></em>\
                        </button>\
                        <button ng-click="grid.appScope.deleteUser(row.entity)" title="删除" class="btn btn-xs btn-danger">\
                            <em class="fa fa-trash"></em>\
                        </button>\
                    </div>\
                '
            }
        ];
        
        $scope.queryParams = {namespace: 'SystemMapper.getAllUsers'};
        $scope.searchUserGrid = function() {
            $scope.currentUser = {};
            userRoleGrid.clear();
            userGrid.draw($scope.queryParams);
        }; 

        var userGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'userGridOptions',
                pageOptionModel: 'userGridPageOptions',
                gridApi: 'userGridApi',
                columns: userGridColumns,
                pageType: 'common',
                needExport: false,
                remoteSort: true,
                controllerSearchFn: $scope.searchUserGrid,
                menus: [
                    {
                        title: '新增',
                        action: function ($event) {
                            userGrid.addRow({status: '1'},0);
                        }
                    }
                ],
                registerApiFn: function(gridApi){
                    gridApi.selection.on.rowSelectionChanged($scope, function (row, event) {
                        $scope.currentUser.id = row.entity.tid;
                        searchUserRoleGrid();
                    });
                }
            }
        );
       
        $scope.saveUser = function(data){
            httpUtils.post('/sysUser/save',data,
                function(result){
                    if (result.success){
                        if (utils.isEmpty(data.tid)){
                            data.tid = result.msg;
                        }
                        toaster.pop('success', '', '保存成功');
                    }else{
                        toaster.pop('error', '', result.msg);
                    }
                },
                function(){
                    toaster.pop('error', '', '保存失败');
                }
            );
        };
        
        $scope.deleteUser = function(data){
            dialogUtils.confirm('确定要删除吗?',
                function () {
                    httpUtils.post('/sysUser/delete',data,
                        function(result){
                            if (result.success){
                                userGrid.deleteRow(data);
                                userRoleGrid.clear();
                                toaster.pop('success', '', '删除成功');
                            }else{
                                toaster.pop('error', '', result.msg);
                            }
                        },
                        function(result){
                            toaster.pop('error', '', '删除失败');
                        }
                    );
                }
            );
        };
        
        $scope.changePassword = function(data){
            ngDialog.openConfirm({
                plain: true,
                template: '\
                    <div class="ngdialog-message">\
                        <h5>新密码</h5>\
                        <p><input ng-model="password"/></p>\
                        <div class="ngdialog-buttons">\
                            <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog()">取消</button>\
                            <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(password)">确定</button>\
                        </div>\
                    </div>\
                '
            }).then(function (password) {
                data.password = password;
                httpUtils.post('/sysUser/changePassword',data,
                    function(result){
                        if (result.success){
                            toaster.pop('success', '', '修改成功');
                        }else{
                            toaster.pop('error', '', result.msg);
                        }
                    },
                    function(result){
                        toaster.pop('error', '', '修改失败');
                    }
                );
            });
        }
        
        $scope.refreshCache = function(){
             httpUtils.get('/sysUser/refreshUserRoleCache',{},
                function(result){
                    if (result.success){
                        toaster.pop('success', '', '刷新成功');
                    }else{
                        toaster.pop('error', '', result.msg);
                    }
                },
                function(){
                    toaster.pop('error', '', '刷新失败');
                }
            );
        }
        
        //选择角色
        $scope.selectRole = function(data){
            ngDialog.openConfirm({
                template: 'selectRoleDialog',
                className: 'ngdialog-theme-default',
                appendClassName: 'ngdialog-lg',
                scope: $scope,
                controller: ['$scope', function($scope) {
                    $scope.searchOtherRoleSelectGrid(data.tid);
                    $scope.searchUserRoleSelectGrid(data.tid);
                }]
            }).then(function (value) {
                var roleIDs = '',
                    selectedRoles = userRoleSelectGrid.getAll();
                
                for (var i = 0; i < selectedRoles.length; i++){
                    roleIDs += selectedRoles[i].tid + ",";
                }
                
                httpUtils.post('/sysUser/saveUserRole',
                    {
                        userID: $scope.currentUser.id,
                        roleIDs: roleIDs
                    },
                    function(result){
                        if (result.success){
                            toaster.pop('success', '', '配置成功');
                            searchUserRoleGrid();
                        }else{
                            toaster.pop('error', '', result.msg);
                        }
                    },
                    function(result){
                        toaster.pop('error', '', '配置失败');
                    }
                );
            });
        }
        
        $scope.goLeft = function(){
            if (otherRoleSelectGrid.getSelection().length > 0){
                for (var i = 0; i < otherRoleSelectGrid.getSelection().length; i++){
                    userRoleSelectGrid.addRow(otherRoleSelectGrid.getSelection()[i]);
                    otherRoleSelectGrid.deleteRow(otherRoleSelectGrid.getSelection()[i]);
                } 
            }   
        }
        
        $scope.goRight = function(){
            if (userRoleSelectGrid.getSelection().length > 0){
                for (var i = 0; i < userRoleSelectGrid.getSelection().length; i++){
                    otherRoleSelectGrid.addRow(userRoleSelectGrid.getSelection()[i]);
                    userRoleSelectGrid.deleteRow(userRoleSelectGrid.getSelection()[i]);
                } 
            }
        }
        
//===========================userRoleGrid=================================        
        var userRoleGridColumns = [
            {
                displayName: '角色编号',
                field: 'code'
            },
            {
                displayName: '角色名称',
                field: 'name'
            },
            {
                displayName: '状态',
                field: 'status',
                width: '80'
            }
        ];
            
        var searchUserRoleGrid = function() {
            if (utils.isEmpty($scope.currentUser.id)){
                userRoleGrid.clear();
            }else {
                var params = {
                    namespace: 'SystemMapper.getUserRole',
                    userID: $scope.currentUser.id
                }

                userRoleGrid.draw(params);
            }
        }; 

        var userRoleGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'userRoleGridOptions',
                gridApi: 'userRoleGridApi',
                needExport: false,
                columns: userRoleGridColumns,
                needPage: false
            }
        );  
 //===========================userRoleSelectGrid=================================                   
        $scope.searchUserRoleSelectGrid = function(id) {
            if (utils.isEmpty(id)){
                userRoleSelectGrid.clear();
            }else {
                var params = {
                    namespace: 'SystemMapper.getUserRole',
                    userID: id
                }

                userRoleSelectGrid.draw(params);
            }
        }; 

        var userRoleSelectGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'userRoleSelectGridOptions',
                gridApi: 'userRoleSelectGridApi',
                needExport: false,
                columns: userRoleGridColumns,
                needPage: false,
                multiSelect: true
            }
        );       
 //===========================otherRoleSelectGrid================================= 
        var otherRoleSelectGridColumns = [
            {
                displayName: '角色编号',
                field: 'code'
            },
            {
                displayName: '角色名称',
                field: 'name'
            }
        ];                 
        $scope.searchOtherRoleSelectGrid = function(id) {
            if (utils.isEmpty(id)){
                otherRoleSelectGrid.clear();
            }else {
                var params = {
                    namespace: 'SystemMapper.getOtherRole',
                    userID: id
                }

                otherRoleSelectGrid.draw(params);
            }
        }; 

        var otherRoleSelectGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'otherRoleSelectGridOptions',
                gridApi: 'otherRoleSelectGridApi',
                needExport: false,
                columns: otherRoleSelectGridColumns,
                needPage: false,
                multiSelect: true
            }
        );  
//===========================init================================= 
        $scope.searchUserGrid();
    }
]);
